package com.ttl.bc.vat.inputtax.db;

import hibernate.util.HibernateUtil;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.ttl.bc.vat.inputtax.bean.BCInputTaxBean;
import com.ttl.common.db.ADAO;

public class BCInputTaxDAO extends ADAO {
	
	@SuppressWarnings("unchecked")
	public List find(String docNo) {
		List result = null;
		Session session = null;

		try {
			SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			
			session.beginTransaction();
			
			Query q = session.createQuery("FROM BCInputTaxBean WHERE docNo='"+docNo+"'");
			//System.out.println(q.list().size());
			result = q.list();
			
			session.getTransaction().commit();						
			
		}catch(Exception e) {			
			System.out.println(e.toString());
		}finally {
			session.close();
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean update(String s, Object o) {
		Session session = null;

		try {
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();

            String hql = "FROM BCInputTaxBean h where h.docNo = '"+s+"'";
            org.hibernate.Query q = session.createQuery(hql);
            List resultList = q.list();			

            for(int i=0; i<resultList.size(); i++){
            	BCInputTaxBean h = (BCInputTaxBean)resultList.get(i);                        
                session.delete(h);
            }
            
            
			session.save(o);
			session.getTransaction().commit();
			return true;
        } catch (HibernateException he) {
            he.printStackTrace();            
			return false;
		} finally {
			session.close();
		}
	}	
	
	@SuppressWarnings("unchecked")
	@Override
	public void delete(String s) {
		Session session = null;

		try {
			SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();			
			session.beginTransaction();
			
			String hql = "FROM BCInputTaxBean h where h.docNo = '"+s+"'";
			Query q = session.createQuery(hql);
			
			ArrayList al = (ArrayList)q.list();
			for(int i=0; i<al.size(); i++) {
				session.delete(al.get(i));
			}			
			
			session.getTransaction().commit();						
						
		}catch(Exception e) {
			System.out.println(e.toString());			
		}finally {
			session.close();
		}
	}
}
